<template>
  <!-- UnlockStep 解锁咨询  -->
  <PageContainer>
    <view class="container">
      <Header title="解锁咨询 " />
      <FullLoading :full-loading="isFullLoading" />
      <OrderStep
        :order-state="orderState"
        :pay-state="payState"
        :refund-status="refundStatus"
        :price="payMoney"
        :payment-end-time="paymentEndTime"
        :suborder="suborderRef"
        @refresh="__init()"
      />
      <!-- 被申请人的联系方式 -->
      <CardBtns
        v-if="orderState === OrderStateEnum.DONE"
        :member-leading-id="suborderRef?.memberLeadingId"
      />
      <DemandDesc v-model="description" :is-textarea="isAppointment" />
      <OrderInfo
        v-if="!isAppointment"
        :create-time="createTime"
        :order-code="orderCodeRef"
        :price="payMoney"
        :pay-time="payTime"
      />

      <BoxTitle title="查看信息">
        <MemberCardItem v-if="suborderRef" :item="suborderRef.memberContactsVo" />
      </BoxTitle>
      <!-- 3天内未审批或审核未通过将全额退款 -->
      <TButtonGroup v-if="getConfirmText">
        <TButton
          v-if="orderState === OrderStateEnum.NOPAYMENT"
          class="gutter-btn"
          text="取消支付"
          :type="'none'"
          custom-class="coopClose"
          @click="cancel"
        />
        <TButton class="gutter-btn" :text="getConfirmText" :type="'primary'" @click="confirm" />
      </TButtonGroup>

      <!-- 关注公众号弹窗 -->
      <TencentCode
        :popupShow="!!useUser.openOfficialAccount"
        :followed-show="false"
        @close="useUser.openOfficialAccount = false"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  UnlockStep  解锁咨询  */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import DemandDesc from '../components/demandDesc.vue';
  import OrderInfo from '../components/orderInfo.vue';
  import { onLoad, redirectTo } from '@/router';
  import { cancellOrder, memberContactsCreateOrder, memberContactsCreateSuborder, getunlockOrderDetail } from '@/api/order';
  import { computed, ref, unref } from 'vue';
  import { type OrderDetails, type UnlockStep } from '@/router/types/modules';
  import { Toast } from '@/utils';
  import { type CreateSuborderResult } from '@/api/order/types';
  import OrderStep from './components/OrderStep.vue';
  import {
    OrderPayStateEnum,
    OrderRefundStatusEnum,
    OrderStateEnum,
    OrderTypeEnum,
  } from '@/enums/orderEnum';
  import FullLoading from '@/components/FullLoading/index.vue';
  import { requestPayment } from '../utils/payment';
  import MemberCardItem from '@/components/ContactsMap/components/MemberCardItem.vue';
  import BoxTitle from '../components/BoxTitle.vue';
  import { onPullDownRefresh } from '@dcloudio/uni-app';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import TencentCode from '@/components/OfficialAccount/tencentCode.vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import CardBtns from './components/CardBtns.vue';

  const useUser = useUserStoreWithOut();

  const pageOptions = ref<UnlockStep>();
  const payMoney = ref<number>();
  const description = ref('');
  const isFullLoading = ref(true);

  const suborderRef = ref<CreateSuborderResult>();
  let callback: OrderDetails['callback'];

  onLoad<'UnlockStep'>((op) => {
    pageOptions.value = op;
    callback = op.callback;
    __init();
  });

  async function __init() {
    const op = unref(pageOptions);
    const id = op?.orderCode || unref(orderCodeRef) || op?.id;
    if (id) {
      // 订单详情逻辑
      await getOrderDetails(id);
    } else {
      await getSubOrder();
    }
    uni.stopPullDownRefresh();
  }

  /** 获取子订单(预约阶段) */
  async function getSubOrder() {
    const op = unref(pageOptions);
    if (!op) return;
    const { orderType, memberLeadingId } = op;
    if (orderType && memberLeadingId) {
      const subOrder = await memberContactsCreateSuborder({ orderType, memberLeadingId });
      if (subOrder.orderCode) return await getOrderDetails(subOrder.orderCode);
      payMoney.value = subOrder.payMoney;
      suborderRef.value = subOrder;

      isAppointment.value = true;
      isFullLoading.value = false;
    } else {
      Toast('参数错误', 'error');
    }
  }

  const isStartOver = ref(false);
  // 订单ID
  const orderId = ref<number>();
  // 订单状态
  const orderState = ref<OrderStateEnum>();
  // 支付状态
  const payState = ref<OrderPayStateEnum>();
  // 退款状态
  const refundStatus = ref<OrderRefundStatusEnum>();
  // 创建时间
  const createTime = ref<string>();
  // 支付结束时间
  const paymentEndTime = ref<string>();
  // 订单号
  const orderCodeRef = ref<string>('');
  // 支付时间
  const payTime = ref<string>();
  // 支付编号
  const payCode = ref<string>();
  const orderType = ref<OrderTypeEnum>();

  /** 获取订单详情 */
  async function getOrderDetails(orderCode: string) {
    orderCodeRef.value = orderCode;
    const res = await getunlockOrderDetail(orderCode);
    orderType.value = res.orderType;

    suborderRef.value = res.suborder;
    orderId.value = res.id;
    orderState.value = res.orderState;
    payState.value = res.payState;
    refundStatus.value = res.refundStatus;
    payMoney.value = res.payMoney;
    createTime.value = res.createTime;
    paymentEndTime.value = res.paymentEndTime;
    payTime.value = res.payTime;
    payCode.value = res.payCode;
    description.value = res.suborder.remark;

    isStartOver.value = res.isSubmitOrder;
    isAppointment.value = false;
    isFullLoading.value = false;
  }

  // 是否是预约阶段(无订单状态)
  const isAppointment = ref(false);
  const getConfirmText = computed(() => {
    if (unref(isAppointment)) return '提交申请';
    if (unref(orderState) === OrderStateEnum.NOPAYMENT) return '支付';
    if (unref(isStartOver)) return '重新发起解锁';
    return '';
  });

  function confirm() {
    if (unref(isStartOver)) {
      redirectTo({
        name: 'unlockStep',
        options: {
          orderType: unref(orderType),
          memberLeadingId: unref(suborderRef)?.memberLeadingId,
        },
      });

      return;
    }

    if (unref(isAppointment)) {
      handelCreateOrder();
    } else if (unref(orderState) === OrderStateEnum.NOPAYMENT) {
      handelToPay();
    }
  }

  function cancel() {
    const id = unref(orderId);
    if (!id) return;
    uni.showModal({
      title: '提示',
      content: '是否立即取消订单?',
      success: (res) => {
        res.confirm &&
          cancellOrder(id).then((r) => {
            Toast('订单取消成功');
            callback?.();
            getOrderDetails(unref(orderCodeRef));
          });
      },
    });
  }

  /** 创建订单(预约) */
  function handelCreateOrder() {
    const op = unref(pageOptions);
    if (!op) return;
    if (!unref(description)) {
      return Toast('请填写申请描述', 'none', 1500);
    }
    const { orderType, memberLeadingId } = op;
    if (orderType && memberLeadingId) {
      memberContactsCreateOrder({
        orderType: orderType,
        memberLeadingId: memberLeadingId,
        remark: unref(description),
      }).then((r) => {
        getOrderDetails(r.orderCode);
      });
    }
  }

  /** 去支付 */
  function handelToPay() {
    if (payMoney.value && payMoney.value <= 0) {
      orderState.value = OrderStateEnum.UNDERWAY;
      callback?.();
    } else {
      payCode.value &&
        requestPayment(payCode.value).then(() => {
          orderState.value = OrderStateEnum.UNDERWAY;
          callback?.();
        });
    }
  }

  onPullDownRefresh(() => {
    __init();
  });
</script>

<style lang="scss" scoped>
  .container {
    padding-bottom: 240rpx;
  }
</style>
